package cn.com.xy.sms.sdk.db.entity;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import cn.com.xy.sms.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.com.xy.sms.sdk.constant.Constant;
import cn.com.xy.sms.sdk.db.DBManager;
import cn.com.xy.sms.sdk.db.XyCursor;
import cn.com.xy.sms.sdk.db.base.BaseManager;
import cn.com.xy.sms.sdk.dex.DexUtil;
import cn.com.xy.sms.sdk.log.LogManager;
import cn.com.xy.sms.sdk.net.NetWebUtil;
import cn.com.xy.sms.sdk.util.JsonUtil;
import cn.com.xy.sms.sdk.util.StringUtils;

public class MatchCacheManager {

    public static final String TABLE_NAME = "tb_match_cache";
    public static final String DROP_TABLE = " DROP TABLE IF EXISTS " + TABLE_NAME;

    /**
     * 获取创建表的sql
     * 
     * @return
     */
    public static String getCreateTableSql() {
        return "create table  if not exists " + TABLE_NAME + " ( "
                + " id INTEGER PRIMARY KEY," + " msg_num_md5 TEXT,"
                + " phonenum TEXT," + " msg_id TEXT," + " scene_id TEXT,"
                + " popup_window_result TEXT," + " bubble_result TEXT," // rich
                                                                        // bubble
                + " session_reuslt TEXT," // simple bubble
                + " card_result TEXT," + " save_time INTEGER DEFAULT '0'," // SMS
                                                                           // RECEIVE
                                                                           // TIME
				+ " value_recognise_result TEXT,"
                + " bubble_lasttime integer default 0," // rich bubble time
                + " session_lasttime integer default 0," // simple bubble time
                + " card_lasttime integer default 0," // card time
                + " recognise_lasttime integer default 0," // recognise last time
                + " EXTEND TEXT,"
        		+ " url_valid_statu integer default 0,"
                + " urls TEXT ,"
                + " urls_result TEXT," 
                /*SDK-720 songzhirong 20170117 start */
                + " urls_lasttime integer default 0,"
                + " is_favorite integer default 0,"//1 is favorite,0 is normal
                + " is_mark integer default 0)";
                /*SDK-720 songzhirong 20170117 end */

    }

    public static final String ADD_recognise_result  = "ALTER TABLE " + TABLE_NAME
            + " ADD COLUMN value_recognise_result  TEXT";
    public static final String ADD_recognise_lasttime = "ALTER TABLE "
            + TABLE_NAME + " ADD COLUMN recognise_lasttime INTEGER DEFAULT '0'";
    public static final String ADD_bubble_lasttime = "ALTER TABLE "
            + TABLE_NAME + " ADD COLUMN bubble_lasttime INTEGER DEFAULT '0'";
    public static final String ADD_session_lasttime = "ALTER TABLE "
            + TABLE_NAME + " ADD COLUMN session_lasttime INTEGER DEFAULT '0'";
    public static final String ADD_card_lasttime = "ALTER TABLE " + TABLE_NAME
            + " ADD COLUMN card_lasttime INTEGER DEFAULT '0'";
    
    public static final String ADD_url_valid_statu = "ALTER TABLE " + TABLE_NAME
            + " ADD COLUMN url_valid_statu INTEGER DEFAULT '0'";
    
    public static final String ADD_urls  = "ALTER TABLE " + TABLE_NAME
            + " ADD COLUMN urls  TEXT";
    
    /*MEIZU-1142 zhaojiangwei 20160908 start*/
    public static final String ADD_URLS_RESULT = "ALTER TABLE " + TABLE_NAME
            + " ADD COLUMN urls_result  TEXT";
    
    public static final String ADD_URLS_LASTTIME = "ALTER TABLE " + TABLE_NAME
            + " ADD COLUMN urls_lasttime INTEGER DEFAULT '0'";
    /*MEIZU-1142 zhaojiangwei 20160908 end*/
    /*SDK-720 songzhirong 20170117 start */
    public static final String ADD_IS_FAVORITE = "ALTER TABLE " + TABLE_NAME
            + " ADD COLUMN is_favorite INTEGER DEFAULT '0'";    
    
    public static final String ADD_IS_MARK = "ALTER TABLE " + TABLE_NAME
            + " ADD COLUMN is_mark INTEGER DEFAULT '0'";   
    /*SDK-720 songzhirong 20170117 end */

    
    public static String getMD5(String phoneNum, String content) {
        try {
            phoneNum = StringUtils.getPhoneNumberNo86(phoneNum);
            if (!StringUtils.isNull(phoneNum) && !StringUtils.isNull(content)) {
                /* SDK-589 huangzhiqiang 20160905 start */
                return StringUtils.getMD5(phoneNum.trim() + content.trim());
                /* SDK-589 huangzhiqiang 20160905 end */
            }
        }
        catch (Throwable e) {
            // TODO: handle Throwable
        }
        return "";
    }

    /***
     * load cahce data by phoneNum
     * 
     * @param phoneNum
     * @return map=key: msg_id value: JSONObject
     */
    public static Map<String, JSONObject> loadDataByParam(String where,
            String args[]) {
        // phoneNum = StringUtils.getPhoneNumberNo86(phoneNum);

        // String [] args= new String[]{phoneNum};
        String[] cols = new String[] { "msg_id", "msg_num_md5",
                "bubble_result", "session_reuslt", "card_result",
                "bubble_lasttime", "session_lasttime", "card_lasttime",
                /*SDK-720 songzhirong 20170117 start */
                "save_time", "value_recognise_result", "recognise_lasttime","urls_result","urls_lasttime","is_favorite","is_mark","phonenum"};
                /*SDK-720 songzhirong 20170117 end */

        XyCursor cursor = null;
        try {
            cursor = DBManager.query(TABLE_NAME, cols, where, args);
            return loadMapDataFromCursor(cols, 0, cursor);
        }
        catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "loadDataByParam: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }finally{
            XyCursor.closeCursor(cursor,true);
        }
        return null;
    }

    public static Map<String, JSONObject> loadDataByParam(String where,
            String args[], String orderBy, String limit) {
        // phoneNum = StringUtils.getPhoneNumberNo86(phoneNum);

        // String [] args= new String[]{phoneNum};
        String[] cols = new String[] { "msg_id", "msg_num_md5",
                "bubble_result", "session_reuslt", "card_result",
                "bubble_lasttime", "session_lasttime", "card_lasttime",
                /*SDK-720 songzhirong 20170117 start */
                "save_time", "value_recognise_result", "recognise_lasttime", "urls_result","urls_lasttime","is_favorite","is_mark","phonenum"};
        		/*SDK-720 songzhirong 20170117 end */

        XyCursor cursor = null;
        try {
            cursor = DBManager.query(TABLE_NAME, cols, where, args, null, null,
                    orderBy, limit);
            return loadMapDataFromCursor(cols, 0, cursor);
        }
        catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "loadDataByParam: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }finally{
            XyCursor.closeCursor(cursor,true);
        }
        return null;
    }
    
    /* RM-920 likuangkuang 20161116 start, add general query interface */
    public static JSONArray loadDataByParam(String[] cols, String where, String args[], String orderBy, String limit) {
        XyCursor cursor = null;
        try {
            cursor = DBManager.query(TABLE_NAME, cols, where, args, null, null, orderBy, limit);
            return loadMapDataFromCursor(cols, cursor);
        } catch (Throwable e) {
            LogManager.w("MatchCacheManager", "loadDataByParam: ", e);
        } finally {
            XyCursor.closeCursor(cursor, true);
        }

        return null;
    }

    private static JSONArray loadMapDataFromCursor(String[] columns, XyCursor cursor){
        JSONArray array = new JSONArray();
        if (cursor != null) {
            try{
                while (cursor.moveToNext()) {
                    JSONObject obj = new JSONObject();
                    int length = columns.length;
                    for (int i = 0; i < length; i++) {
                        obj.put(columns[i], StringUtils.getNoNullString(cursor.getString(i)));
                    }

                    handObjData(obj);
                    array.put(obj);
                }

                return array;
            } catch (Throwable t) {
                LogManager.w("MatchCacheManager", "loadMapDataFromCursor", t);
            }
        }

        return null;
    }
    /* RM-920 likuangkuang 20161116 end */
    /*MEIZU-1142 zhaojiangwei 20160908 start*/
	public static Map<String, JSONObject> loadDataByParam(String where, String args[], String[] cols) {
		XyCursor cursor = null;
		try {
			cursor = DBManager.query(TABLE_NAME, cols, where, args);
			return loadMapDataFromCursor(cols, 0, cursor);
		}
		catch (Throwable e) {
			/* SDK-550 hewengao 20160719 start */
			LogManager.w(Constant.TAG, "loadDataByParam: ", e);
			/* SDK-550 hewengao 20160719 end */
		}
		finally {
			XyCursor.closeCursor(cursor, true);
		}
		return null;
	}
	/*MEIZU-1142 zhaojiangwei 20160908 end*/
    
    /**
     * 加载数据,从数据游标中
     * @param columns 需要加载的数据列
     * @param cursor 游标
     * @return Map<String, JSONObject> 数据集
     */
    private static Map<String, JSONObject> loadMapDataFromCursor(String[] columns,int keyIndex,XyCursor cursor){
         if(cursor != null){
                try{
                JSONObject  tempObj =null;
                Map<String, JSONObject> res = new HashMap<String,JSONObject>();
                while(cursor.moveToNext()){
                    tempObj = new JSONObject();
                    for(int i =0; i< columns.length;i++){
                        tempObj.put(columns[i],StringUtils.getNoNullString(cursor.getString(i)));
                    }
                    handObjData(tempObj);
                    res.put((String)JsonUtil.getValueFromJsonObject(tempObj, columns[keyIndex]),tempObj);
                   
                }
                 return res;
                }catch(Throwable e){
                    /*sdk-593 hewengao/20160819 start*/
                    LogManager.w("BaseManager", "loadMapDataFromCursor Throwable=",e);
                    /*sdk-593 hewengao/20160819 end*/
                }finally{
                     
                }
            }
            return null;
    }
    
    private static  void handObjData(JSONObject jsObj){
        //hand rich bubble 
        String data = (String) JsonUtil.getValueFromJsonObject(jsObj, "bubble_result");
        try {
        	/*SDK-684 zhaojiangwei 20161124 start */
        	long lastTime = JsonUtil.getLongValueFromJsonObject(jsObj,"bubble_lasttime");
        	/*SDK-684 zhaojiangwei 20161124 end */
            if (!StringUtils.isNull(data)) {
//                final  long CACHETIME_15_DAY = 1296000000;// 15天
//                if (System.currentTimeMillis() - lastTime < CACHETIME_15_DAY) {// 没有超过有效期,不需要重新走识别流程  // 15天
            	  //历史已识别过的短信，需要招回走立即 招回指令
                    JSONObject dataArr = new JSONObject(data);
                    jsObj.put("bubble_result", dataArr);
//                }else{
//                    jsObj.remove("bubble_result");
//                    jsObj.put("need_parse_bubble","");
//                }
            } else {
                jsObj.remove("bubble_result");
                final long CACHETIME = getReparseBubbleCycle(); // 默认值是6个小时
                if (lastTime != 0 && System.currentTimeMillis() - lastTime < CACHETIME) {
 
                }else{
                    jsObj.put("need_parse_bubble","");
                }
            }
        }catch(Throwable e){
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "handObjData: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        //hand simple bubble 
        data = (String) JsonUtil.getValueFromJsonObject(jsObj, "session_reuslt");
        try {
        	/*SDK-684 zhaojiangwei 20161124 start */
        	long lastTime = JsonUtil.getLongValueFromJsonObject(jsObj,"session_lasttime");
        	/*SDK-684 zhaojiangwei 20161124 end */
            if (!StringUtils.isNull(data)) {
            	
//                final  long CACHETIME_15_DAY = 1296000000;// 15天
//                if (System.currentTimeMillis() - lastTime < CACHETIME_15_DAY) {// 没有超过有效期,不需要重新走识别流程 // 15天
            	    //历史已识别过的短信，需要招回走立即 招回指令
                    JSONArray dataArr = new JSONArray(data);
                    jsObj.put("session_reuslt", dataArr);
//                }else{
//                    jsObj.remove("session_reuslt");
//                    jsObj.put("need_parse_simple","");
//                    LogManager.e("duoqu_xiaoyuan","simple data: "+data+" lastTime: "+lastTime+" session_result: is null.");
//                }
            } else {
                jsObj.remove("session_reuslt");
                final long CACHETIME = getReparseBubbleCycle(); // 默认值是6个小时
                if (lastTime != 0 && System.currentTimeMillis() - lastTime < CACHETIME) {
                    
                }else{
                    jsObj.put("need_parse_simple","");
                }
            }
        }catch(Throwable e){
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "handObjData: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        
        //handle recognise value
        data = (String) JsonUtil.getValueFromJsonObject(jsObj, "value_recognise_result");
        try {
        	/*SDK-684 zhaojiangwei 20161124 start */
            long lastTime = JsonUtil.getLongValueFromJsonObject(jsObj,"recognise_lasttime");
            /*SDK-684 zhaojiangwei 20161124 end */
            if (!StringUtils.isNull(data)) {
                    JSONObject dataObj = new JSONObject(data);
                    jsObj.put("value_recognise_result", dataObj);
            } else {
                jsObj.remove("value_recognise_result");
                final long CACHETIME = getReparseBubbleCycle(); // 默认值是6个小时
                if (lastTime != 0 && System.currentTimeMillis() - lastTime < CACHETIME) {
                    
                }else{
                    jsObj.put("need_parse_recognise","");
                }
            }
        }catch(Throwable e){
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "handObjData: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }
    public static JSONObject getDataByParam(String msgId) {
        String[] cols = new String[] { "msg_id", "msg_num_md5",
                "bubble_result", "session_reuslt", "card_result",
                "bubble_lasttime", "session_lasttime", "card_lasttime",
                /*SDK-720 songzhirong 20170117 start */
                "save_time", "value_recognise_result", "recognise_lasttime","urls_result","urls_lasttime","is_favorite","is_mark","phonenum" };
                /*SDK-720 songzhirong 20170117 end */

        XyCursor cursor = null;
        try {
            cursor = DBManager.query(TABLE_NAME, cols, "msg_id=?", 
                    new String[]{msgId}, null, null,
                    null, null);
            JSONObject obj= BaseManager.loadSingleDataFromCursor(cols, cursor);
            if(obj != null){
                handObjData(obj);
            }
            return obj;
        }
        catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "getDataByParam: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }finally{
              XyCursor.closeCursor(cursor,true);
        }
        return null;
    }
    
    public static void updateCheckStatu(JSONArray jsonArray){
    	try {
    		if(jsonArray==null||jsonArray.length()<=0)return;
	    	for(int i=0;i<jsonArray.length();i++){
	    		JSONObject json = jsonArray.optJSONObject(i);
	    		String url = json.optString("originURL");
	    		int  statu = json.optInt("validStatus");
	    		
	    		ContentValues values = new ContentValues();
	            values.put("url_valid_statu", statu);
	    		DBManager.update(TABLE_NAME, values, " urls = ? ", new String[] { url });
	    		
	    	}	    	
    	
		} catch (Throwable e) {
			// TODO: handle exception
		}    	
    }
    
    public static void updateCheckStatu(String url,int checkStatu){
    	try {
    		ContentValues values = new ContentValues();
            values.put("url_valid_statu", checkStatu);
    		DBManager.update(TABLE_NAME, values, " urls = ? ", new String[] { url });
		} catch (Throwable e) {
			// TODO: handle exception
		}    	
    }

    /**
     * @param values
     * @param dataType
     *            1: simple bubble data 2:rich bubble data 3:popupwindow data
     * @return
     */
    /* SDK-700 zhaojiangwei 20161209 start */
    public static synchronized long insertOrUpdate(ContentValues values, int dataType) {
    /* SDK-700 zhaojiangwei 20161209 end */	
        long result = -1;
        XyCursor cur =null;
        try {
            String msg_id = (String) values.get("msg_id");
            String msg_num_md5 = (String) values.get("msg_num_md5");
            if (!StringUtils.isNull(msg_id)) {
                // delete old data
                String[] args = new String[] { msg_id };
                String[] cols = new String[] { "msg_num_md5", "id" };
                cur = DBManager.query(TABLE_NAME, cols, " msg_id = ? ", args);
                JSONObject data = BaseManager.loadSingleDataFromCursor(cols,cur);
                String msgNumMd5 = null;
                if (data != null) {
                    msgNumMd5 = (String) JsonUtil.getValueFromJsonObject(data,"msg_num_md5");
                    result = Long.valueOf((String) JsonUtil.getValueFromJsonObject(data, "id"));
                }
                if (msgNumMd5 == null || !msgNumMd5.equals(msg_num_md5)) {
                    // old and new data is not same need delete old and insert
                    // new
                    if (msgNumMd5 != null) {
                        DBManager.delete(TABLE_NAME, " msg_id = ? ", args);
                    }
                    // insert new data
                    result = DBManager.insert(TABLE_NAME, values);
                } else {
                    // update old data
                    DBManager.update(TABLE_NAME, values, " msg_id = ? ", args);
                }
            }
        }
        catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "insertOrUpdate: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        finally {
            XyCursor.closeCursor(cur, true);
            cur = null;
        }
        return result;

    }
    
	public static void resetRecognisedResult(String msgId) {
		if (StringUtils.isNull(msgId)) {
			return;
		}
		ContentValues matchCacheValues = BaseManager.getContentValues(null, "msg_id", msgId, "value_recognise_result",
				"", "recognise_lasttime", "0");
		String[] args = new String[] { msgId };
		 // update old data
        try {
			DBManager.update(TABLE_NAME, matchCacheValues, " msg_id = ? ", args);
		}
		catch (Throwable e) {
			// TODO Auto-generated catch block
            /* SDK-550 hewengao 20160719 start */
            LogManager.w("duoquTest", "MatchCacheManager.resetRecognisedResult, exception:", e);
            /* SDK-550 hewengao 20160719 start */
		}
        
	}
    
    public static boolean deleteBubbleData(String msgId,String md5){
        if(StringUtils.isNull(msgId)){
            return false;
        }
        int rows= -1;
        try {
            if(StringUtils.isNull(md5)){
                rows= DBManager.delete(TABLE_NAME, " msg_id = ? ", new String[]{msgId});
            }
            else{
                rows= DBManager.delete(TABLE_NAME, " msg_id = ? and msg_num_md5 = ? ", new String[]{msgId,md5});
            }
        } catch (Throwable e) {
            // TODO Auto-generated catch block
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteBubbleData: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
        if(rows > 0){
            return true;
        }
        return false;
    }
    
    /**
     * 根据短信id及短信号码与内容MD5判断是否存在相同的数据
     * 
     * @param smsId 短信id
     * @param msgNumMd5 短信号码与内容MD5
     * @return
     */
    public static int queryDataCount(String smsId, String msgNumMd5) {
        XyCursor cursor = null;
        try {
            cursor = DBManager.query(TABLE_NAME, new String[] { "id" }, "msg_num_md5 = ? AND msg_id = ?",
                    new String[] { smsId, msgNumMd5 });
            if (cursor != null && cursor.moveToNext()) {
                return cursor.getCount();
            }
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "queryDataCount: ", e);
            /*SDK-550 hewengao 20160719 end*/
        } finally {
            XyCursor.closeCursor(cursor, true);
        }
        return 0;
    }
    
    public static int deleteDataByPhoneNum(String phoneNum){
    	 if(!StringUtils.isNull(phoneNum)){
             try {
				return DBManager.delete(TABLE_NAME, " phonenum = ? ", new String[]{phoneNum});
			} catch (Throwable e) {
//				e.printStackTrace();
			    /*SDK-550 hewengao 20160719 start*/
                LogManager.w(Constant.TAG, "deleteDataByPhoneNum: ", e);
                /*SDK-550 hewengao 20160719 end*/
			}
         }
    	 return -1;
    }
    
    public static void deleteDataByMsgIds(Set<Integer> ids){

    	if(ids!=null&&!ids.isEmpty())
    	{
    		synchronized (DBManager.dblock) {
                SQLiteDatabase db = null;
                try {
                    db = DBManager.getSQLiteDatabase();
                    
                	StringBuffer sb = new StringBuffer();
            		Iterator<Integer> it = ids.iterator();  
            		while (it.hasNext()) {  
            		  Integer str = it.next();  
            		  sb.append(str+",");
            		}  
            		sb.deleteCharAt(sb.length()-1);
            		
                    String sql = "DELETE FROM tb_match_cache WHERE msg_id IN ("+sb.toString()+")";
                    db.execSQL(sql);
                } catch (Throwable e) {
//                    e.printStackTrace();
                    /*SDK-550 hewengao 20160719 start*/
                    LogManager.w(Constant.TAG, "deleteDataByMsgIds: ", e);
                    /*SDK-550 hewengao 20160719 end*/
                } finally {
                    DBManager.close(db);
                }
            }
    	}
    }
    /**
     * 删除无用的KEY
     * @param obj
     */
    public static void removeUselessKey(JSONObject obj){
    	if(obj == null){
    		return;
    	}
    	try{	
    		String [] keys ={"version","layoutName","ALLOW_VERCODE_MSG",
    				"smsCenterNum","channel","RECOGNIZE_LEVEL","is_return","viewPartParam","simIndex"};
    		for(String key :keys){
    			if(obj.has(key)){
    				obj.remove(key);
    			}
    		}
	    }catch(Throwable e){
//	    	e.printStackTrace();
	        /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "removeUselessKey: ", e);
            /*SDK-550 hewengao 20160719 end*/
	    }
    }
    
    public static void deleteMatchCache(String sceneId, long endParseTime) {
        try {
        	int result = -1;
        	StringBuffer whereArgs=new StringBuffer(" bubble_lasttime < ?");
        	if(sceneId.length()  ==8){
        		whereArgs.append(" and scene_id = ? ");
        	}else{
        		whereArgs.append(" and scene_id like '?%' ");
        	}
        	result = DBManager.delete(TABLE_NAME, whereArgs.toString(), new String[] { 
	                    String.valueOf(endParseTime),sceneId});
         } catch (Throwable e) {
//            e.printStackTrace();
             /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteMatchCache: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }
    
    public static void deleteMatchCache(String sceneId,String clName,long endParseTime) {
        try {
        	int result = -1;
        	StringBuffer whereArgs=new StringBuffer(clName+"  < ?");
        	if(StringUtils.isNull(sceneId))
        	{
        		whereArgs.append(" and (scene_id is null or length(scene_id) = 0) ");
        		
        		result = DBManager.delete(TABLE_NAME, whereArgs.toString(), new String[] { 
                    String.valueOf(endParseTime)});
        	}
        	else
        	{
        		if(sceneId.length()  ==8){
            		whereArgs.append(" and scene_id = ? ");
            		
            		result = DBManager.delete(TABLE_NAME, whereArgs.toString(), new String[] { 
                        String.valueOf(endParseTime),sceneId});
            		
            	}else{
            		whereArgs.append(" and scene_id like '"+sceneId+"%' ");
            		
            		result = DBManager.delete(TABLE_NAME, whereArgs.toString(), new String[] { 
                        String.valueOf(endParseTime)});
            	}
        	}
        } catch (Throwable e) {
//            e.printStackTrace();
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteMatchCache: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }
    
    /**
     * 获取气泡识别失败重新识别短信周期，默认值是6个小时
     * 
     * @return
     */
    private static long getReparseBubbleCycle() {
        String strReparseBubbleCycle = SysParamEntityManager.getStringParam(Constant.getContext(),
                Constant.REPARSE_BUBBLE_CYCLE);
        long reparseBubbleCycle = -1;
        if (!"-1".equals(strReparseBubbleCycle)) {
            try {
                reparseBubbleCycle = Long.parseLong(strReparseBubbleCycle);
            } catch (Exception ex) {
            }
        }

        if (reparseBubbleCycle > 0) {
            return reparseBubbleCycle;
        }

        return DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REPARSE_BUBBLE_CYCLE, 21600000L);
    }
    
    public static void deleteAll(){
    	try {
    		DBManager.delete(TABLE_NAME, null,null);
		} catch (Throwable e) {
//			e.printStackTrace();
		    /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "deleteAll: ", e);
            /*SDK-550 hewengao 20160719 end*/
		}
    }

    /* SDK-695 huangzhiqiang 20161207 begin */
    /**
     * 丰富气泡数据缓存入库
     * 
     * @throws JSONException
     */
    public static void updateMatchCacheManager(String phoneNumber, String titleNo, String msgId,
            JSONObject bubbleResult, String messageBody) throws JSONException {
        updateMatchCacheManager(phoneNumber, titleNo, msgId, bubbleResult, null, messageBody);
    }

    /**
     * 丰富气泡、简单气泡数据缓存入库
     * 
     * @throws JSONException
     */
    public static void updateMatchCacheManager(String phoneNumber, String titleNo, String msgId,
            JSONObject bubbleResult, JSONArray sessionReuslt, String messageBody) throws JSONException {
        if ((bubbleResult == null || bubbleResult.length() == 0)
                && (sessionReuslt == null || sessionReuslt.length() == 0)) {
            return;
        }
        String msgNumMd5 = MatchCacheManager.getMD5(phoneNumber, messageBody);
        if (StringUtils.isNull(msgNumMd5)) {
            return;
        }
        String currentTimeMillis = String.valueOf(System.currentTimeMillis());
        ContentValues contentValues = new ContentValues();
        contentValues.put("msg_num_md5", msgNumMd5);
        contentValues.put("phonenum", StringUtils.getPhoneNumberNo86(phoneNumber));
        contentValues.put("scene_id", titleNo);
        contentValues.put("msg_id", msgId);
        contentValues.put("save_time", currentTimeMillis);
        if (bubbleResult != null) {
            JSONObject newBubbleResult = new JSONObject(bubbleResult.toString());
            MatchCacheManager.removeUselessKey(newBubbleResult);
            contentValues.put("bubble_result", newBubbleResult.toString());
            contentValues.put("bubble_lasttime", currentTimeMillis);
        }
        if (sessionReuslt != null) {
            contentValues.put("session_reuslt", sessionReuslt.toString());
            contentValues.put("session_lasttime", currentTimeMillis);
        }
        updateMatchCacheManager(contentValues);
    }

    /**
     * 识别数据入库
     * 
     */
    public static void updateMatchCacheManager(final ContentValues contentValues) {
        if (contentValues == null) {
            return;
        }
        NetWebUtil.executeRunnable(new Runnable() {
            @Override
            public void run() {
                try {
                    MatchCacheManager.insertOrUpdate(contentValues, 5);
                } catch (Throwable e) {
                    LogManager.w("updateMatchCacheManager", "updateMatchCache error", e);
                }
            }
        });
    }
    /* SDK-695 huangzhiqiang 20161207 end */

    /* SDK-442 huangzhiqiang 20160518 start */
    /**
     * 重置识别失败的短信的最后识别时间
     * 
     * @param lastParseTime
     */
    public static void resetLastParseTime(long lastParseTime) {
        try {
            updateLastTime("bubble_result", "bubble_lasttime", lastParseTime);
            updateLastTime("session_reuslt", "session_lasttime", lastParseTime);
            updateLastTime("card_result", "card_lasttime", lastParseTime);
            updateLastTime("value_recognise_result", "recognise_lasttime", lastParseTime);
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "MatchCacheManager resetLastParseTime error:" , e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }

    /**
     * 更新最后识别时间
     * 
     * @param resultField 识别结果字段
     * @param lastTimeField 最后识别时间字段
     * @param lastTime 最后识别时间
     */
    private static void updateLastTime(String resultField, String lastTimeField, long lastTime) {
        try {
            DBManager.update(TABLE_NAME, BaseManager.getContentValues(null, lastTimeField, String.valueOf(lastTime)), resultField + " IS NULL OR " + resultField + "=''", null);
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "MatchCacheManager updateLastTime error:" , e);
            /*SDK-550 hewengao 20160719 end*/
        }
    }
    /* SDK-442 huangzhiqiang 20160518 end */
    
    /*SDK-720 songzhirong 20170117 start */
    public static void updateMarkAndFavoriteAsy(final String msgId,final String phone,
    		final String content,final int mark,final int isFavoite){
    	
    	 NetWebUtil.executeRunnable(new Runnable() {
             @Override
             public void run() {
                 try {
                	   ContentValues contentValues = new ContentValues();
                       contentValues.put("is_mark", mark);
                       contentValues.put("is_favorite", isFavoite);
                       
                       String md5 = MatchCacheManager.getMD5(phone, content);
                       
                       String where = "msg_id = ? and msg_num_md5 = ?";
                       String args[] = new String[] { msgId, md5};
                       
                       DBManager.update(TABLE_NAME, contentValues, where, args);
                       
                 } catch (Throwable e) {
                     LogManager.w("updateMarkAndFavoriteAsy", "updateMarkAndFavoriteAsy error", e);
                 }
             }
         });
    }
    /*SDK-720 songzhirong 20170117 end */
}
